#!/bin/sh
# chkconfig: 2345 87 88
# Description: huidu-go-ulive-app service


APP_HOME="main"
prog=main
start_scripts_name="main"
process="./main"

function startSer() {
    chmod +x ${start_scripts_name}
    cd ${APP_HOME} && nohup ./${start_scripts_name} > output.log 2>&1 &
    if [ $? -eq 0 ];then
        echo "Starting $prog Server" #/bin/true
    else
        echo "Starting $prog Server" #/bin/false
    fi
}

function stopSer() {

    PID=$(ps aux | grep -w ${process} | grep -v grep | awk '{print $2}')
    if [ "${PID}" ];then
      time=2
      time_interval=0.5
      TIME_NUM=$(echo "${time} ${time_interval}" | awk '{print $1 / $2}')
      echo "次数 $TIME_NUM"
      kill -2 ${PID}
      i=0
      while(( $i<=$TIME_NUM ))
      do
          PID=$(ps aux | grep -w ${process} | grep -v grep | awk '{print $2}')
          if [ "$PID" ];then
              [ $i == ${TIME_NUM} ] && kill -9 $PID || sleep ${time_interval}
              echo "pid为: $PID"
          else
              echo "平滑退出,break"
              break
          fi
        let "i++"
      done
    fi

    # [ $? -eq 0 ] && action "Stop $prog Server" /bin/true || action "Stop $prog Server" /bin/false
}

function status() {
    PID=$(ps aux | grep -w ${process} | grep -v grep | awk '{print $2}')
    if [ "$PID" ];then
        if kill -0 $PID > /dev/null 2> /dev/null ; then
            return 0
        else
            return 2 # program is dead but pid file exists
        fi
    else
        return 3 # program is not running
    fi
}



case "$1" in
  start)
     status
     code=$?
     if [ $code -eq 0 ]; then
         echo "$prog server is already running"
     else
         startSer
         code=$?
     fi
     exit $code
     ;;
  stop)
     stopSer
     ;;
  restart)
     stopSer
     startSer
     ;;
  status)
    status
     if [ $? -eq 0 ];then
         echo -e "$prog server \033[32mRunning\033[0m (PID:$PID)..."
     else
         echo -e "$prog server \033[31m Not running\033[0m..."
     fi
     ;;
  *)
     echo "Usage: service $prog {start|stop|restart|status}"
     exit 1
esac

exit 0


